package top.itaso.lib.net.rtf2;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import top.itaso.lib.net.ConfigKeys;
import top.itaso.lib.net.NetInit;
import top.itaso.lib.net.callback.IInterceptorParamsSet;
import top.itaso.lib.net.log.LogUtils;

/**
 * @Description: 拦截器常用模板以及一些信息的打印
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Github https://github.com/itsdf07
 * @Date 2020/11/3
 */
class MyLogInterceptor implements Interceptor {
    private static final String TAG = MyLogInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        if (!LogUtils.isLog()) {
            return chain.proceed(chain.request());
        }
        LogUtils.logd(TAG + " Interceptor 常用模板可参考 top.itaso.lib.net.interceptor 包下所提供");
        //--------------------输出原始 Request 的信息--------------------------------------------
        // 拦截请求，获取到该次请求的request
        Request request = chain.request();
        String method = request.method();//如：POST
        String host = request.url().host();//如：api.itaso.top
        String url = request.url().toString();//如：http://api.itaso.top/api/user/sendVerifyCode2Email
        boolean isHttps = request.url().isHttps();//如：false
        String scheme = request.url().scheme();//如：http
        // MyLogInterceptor intercept: 原始请求 Request 中 method=POST,host=api.itaso.top,isHttps=false,scheme=http,url=http://api.itaso.top/api/user/login
        LogUtils.logd(TAG + " intercept: 原始请求 Request 中 method=" + method + ",host=" + host + ",isHttps=" + isHttps + ",scheme=" + scheme + ",url=" + url);

        RequestBody requestBody = request.body();
        if (requestBody == null) {
            return chain.proceed(request);
        }
        // MyLogInterceptor intercept: 原始请求 Request 中的 header={channel=[00001],clientos=[1],pkgname=[top.itaso.app],version=[1.0],}
        LogUtils.logd(TAG + " intercept: 原始请求 Request 中的 header={" + requestHeaders2Log(request) + "}");

        Buffer requestBodyBuffer = new Buffer();
        requestBody.writeTo(requestBodyBuffer);
        String requestBodySource = requestBodyBuffer.readByteString().utf8();
        // MyLogInterceptor intercept: 原始请求 Request 中的 body={"passwd":"111111","loginType":"2","username":"923255742@qq.com","channel":"00001","pkgName":"top.itaso.app","clientOs":1,"version":"1.0"}
        LogUtils.logd(TAG + " intercept: 原始请求 Request 中的 body=" + requestBodySource);

        //----------------------重构新的 Request 对象，并输出重构后的信息------------------------------------------
        final Request.Builder newBuilder = request.newBuilder();
        //BridgeInterceptor.java 的部分内容用来填充点 Header 数据，以便打印 Header 信息
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            newBuilder.header("Content-Type", contentType.toString());
        }
        long contentLength = requestBody.contentLength();
        if (contentLength != -1) {
            newBuilder.header("Content-Length", Long.toString(contentLength));
        }

        //追加参数
        IInterceptorParamsSet interceptorParamsSet = NetInit.getConfiguration(ConfigKeys.INTERCEPTOR_PARAMS_SET.name());
        if (interceptorParamsSet != null) {
            //---------------请求头参数处理
            HashMap<String, String> headerParams = interceptorParamsSet.headerParams();
            if (headerParams != null) {
                Iterator iterator = headerParams.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    if (entry == null || entry.getValue() == null) {
                        continue;//数据不正常时跳过
                    }
                    String key = entry.getKey().toString();
                    if (!TextUtils.isEmpty(request.headers().get(key))) {
                        continue;//追加头已经在存在，则跳过
                    }
                    String value = entry.getValue().toString();
                    newBuilder.addHeader(key, value);
                }
            }
            //---------------请求体参数处理
            HashMap<String, String> bodyParams = interceptorParamsSet.headerParams();
            String newBody = "";
            if (bodyParams != null) {
                if (request.body() instanceof RequestBody) {
                    try {
                        JSONObject newRequestBodyJson = new JSONObject(requestBodySource);
                        Iterator iterator = bodyParams.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry entry = (Map.Entry) iterator.next();
                            if (entry == null || entry.getValue() == null) {
                                continue;//数据不正常时跳过
                            }
                            String key = entry.getKey().toString();
                            if (!TextUtils.isEmpty(newRequestBodyJson.getString(key))) {
                                continue;//追加参数已经在存在，则跳过
                            }
                            String value = entry.getValue().toString();
                            newRequestBodyJson.put(key, value);
                        }
                        newBody = newRequestBodyJson.toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (request.body() instanceof FormBody) {//表单提交
                    FormBody body = (FormBody) request.body();
                    StringBuffer formBodyEncode = new StringBuffer();
                    StringBuffer formBody = new StringBuffer();
                    //封装参数
                    for (int i = 0; i < body.size(); i++) {
                        formBodyEncode.append((i + 1) + "-" + body.encodedName(i) + ":" + body.encodedValue(i) + ",");
                        formBodyEncode.append((i + 1) + "-" + body.name(i) + ":" + body.value(i) + ",");
                    }
                    LogUtils.logd(TAG + " intercept: >>>>>>FormBody={" + formBodyEncode.toString() + "}");
                    LogUtils.logd(TAG + " intercept: >>>>>>FormBody={" + formBody.toString() + "}");
                } else if (request.body() instanceof MultipartBody) {
                    LogUtils.logd(TAG + " intercept: >>>>>>MultipartBody=");
                } else {
                    LogUtils.logd(TAG + " intercept: >>>>>>other=");
                }
            }
            if (!TextUtils.isEmpty(newBody)) {
                // MyLogInterceptor intercept: 新构建的 Request 中的 Json 格式 body={"passwd":"111111","loginType":"2","username":"923255742@qq.com","channel":"00001","pkgName":"top.itaso.app","clientOs":1,"version":"1.0"}
                LogUtils.logd(TAG + " intercept: 新构建的 Request 中的 Json 格式 body=" + newBody);
                newBuilder.method(request.method(), RequestBody.create(MediaType.parse(contentType.toString()), newBody));//重构 RequestBody
            }
        }

        Request newRequest = newBuilder.build();
        // MyLogInterceptor intercept: 新构建的 Request 中的 header={channel=[00001],clientos=[1],content-length=[138],content-type=[application/json; charset=utf-8],pkgname=[top.itaso.app],version=[1.0],}
        LogUtils.logd(TAG + " intercept: 新构建的 Request 中的 header={" + requestHeaders2Log(newRequest) + "}");

//        return chain.proceed(newBuilder.build());//使用新构造的 Request 时启用
        return chain.proceed(request);
    }

    private String requestHeaders2Log(Request request) {
        if (!LogUtils.isLog()) {
            return "";
        }
        Iterator requestIteratorHeader = request.headers().toMultimap().entrySet().iterator();
        StringBuilder requestHeaders = new StringBuilder();
        while (requestIteratorHeader.hasNext()) {
            Map.Entry entry = (Map.Entry) requestIteratorHeader.next();
            if (entry == null || entry.getKey() == null || entry.getValue() == null) {
                continue;//数据不正常时跳过
            }
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            requestHeaders.append(key + "=" + value + ",");
        }
        return requestHeaders.toString();
    }
}
